<!-- 新增/编辑证书模板2 --> 
<template>
  <el-dialog
    :title="dialogTitle"
    :visible="visible"
    width="1000px"
    @close="handleClose"
    append-to-body
  >
    <div class="main-container">
      <!-- 左侧设置区域 -->
      <div class="left-panel">
        <el-form ref="form" :model="formData" label-width="100px">
          <!-- 证书字段配置 -->
          <div class="section">
            <h1>证书字段</h1>
            <div class="field-list">
              <div
                v-for="(field, index) in certificateFields"
                :key="index"
                class="field-item"
              >
                {{ field.label }}
                <i
                  class="el-icon-close"
                  @click="removeCertificateField(index)"
                />
              </div>
            </div>
          </div>

          <!-- 自定义字段 -->
          <div class="section">
            <h1>自定义字段</h1>
            <div class="custom-field-list">
              <div
                v-for="(customField, index) in customFields"
                :key="index"
                class="custom-field-item"
              >
                <span>{{ customField.value }}</span>
                <el-button
                  size="mini"
                  type="text"
                  @click="deleteCustomField(index)"
                  >删除</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  @click="editCustomField(index)"
                  >编辑</el-button
                >
              </div>

              <!-- 新增自定义字段 -->
              <div class="add-custom-field">
                <el-input
                  v-model="newCustomField"
                  placeholder="请输入自定义字段"
                  style="width: 200px; margin-right: 10px"
                />
                <el-button size="mini" @click="addCustomField">确定</el-button>
              </div>
            </div>
          </div>

          <!-- 格式设置 -->
          <div class="section">
            <h1>格式设置</h1>
            <div class="format-container">
              <!-- 字体选择 -->
              <div class="format-group">
                <label>字体：</label>
                <el-select v-model="format.fontFamily" style="width: 100%">
                  <el-option label="黑体" value="SimHei" />
                  <el-option label="宋体" value="SimSun" />
                  <el-option label="微软雅黑" value="Microsoft YaHei" />
                </el-select>
              </div>

              <!-- 字号选择 -->
              <div class="format-group">
                <label>字号：</label>
                <el-select v-model="format.fontSize" style="width: 100%">
                  <el-option label="12" value="12" />
                  <el-option label="14" value="14" />
                  <el-option label="16" value="16" />
                  <el-option label="18" value="18" />
                  <el-option label="20" value="20" />
                </el-select>
              </div>

              <!-- 字体颜色 -->
              <div class="format-group">
                <label>颜色：</label>
                <el-color-picker
                  v-model="format.color"
                  show-alpha
                  style="
                    width: 120px;
                    display: inline-block;
                    vertical-align: middle;
                  "
                />
              </div>

              <!-- 字体样式    补充：实现不完整 -->
              <div class="format-group">
                <label>样式：</label>
                <div
                  class="style-buttons"
                  style="display: flex; gap: 8px; align-items: center"
                >
                  <!-- 加粗 -->
                  <el-button
                    @click="toggleBold(!format.bold)"
                    :class="{ active: format.bold }"
                    type="text"
                  >
                    <span style="font-weight: bold">T</span>
                  </el-button>

                  <!-- 斜体 -->
                  <el-button
                    @click="toggleItalic(true)"
                    :class="{ active: format.italic }"
                    type="text"
                  >
                    <span style="font-style: italic">T</span>
                  </el-button>

                  <!-- 下划线 -->
                  <el-button
                    @click="toggleUnderline(!format.underline)"
                    :class="{ active: format.underline }"
                    type="text"
                  >
                    <span style="text-decoration: underline">T</span>
                  </el-button>

                  <!-- 上标 -->
                  <!-- <el-button
                    @click="toggleSuperscript(!format.superscript)"
                    :class="{ active: format.superscript }"
                    type="text"
                  >
                    <span style="vertical-align: super">T<sup>1</sup></span>
                  </el-button> -->

                  <!-- 下标 -->
                  <!-- <el-button
                    @click="toggleSubscript(!format.subscript)"
                    :class="{ active: format.subscript }"
                    type="text"
                  >
                    <span style="vertical-align: sub">T<sub>1</sub></span>
                  </el-button> -->
                </div>
              </div>

              <!-- 文本对齐 -->
              <div class="format-group">
                <label>对齐：</label>
                <el-radio-group v-model="format.alignment">
                  <el-radio-button label="left">左对齐</el-radio-button>
                  <el-radio-button label="center">居中</el-radio-button>
                  <el-radio-button label="right">右对齐</el-radio-button>
                </el-radio-group>
              </div>

              <!-- 字间距 -->
              <div class="format-group">
                <label>字间距：</label>
                <el-slider
                  v-model="format.letterSpacing"
                  :min="0"
                  :max="5"
                  :step="0.1"
                />
                <span>{{ format.letterSpacing }}px</span>
              </div>

              <!-- 背景色设置 -->
              <!-- <div class="format-group">
                <label>背景色：</label>
                <el-color-picker v-model="format.backgroundColor" show-alpha />
              </div> -->

              <!-- 边框色设置 -->
              <!-- <div class="format-group">
                <label>边框色：</label>
                <el-color-picker v-model="format.borderColor" show-alpha />
              </div> -->

              <!-- 行高 -->
              <div class="format-group">
                <label>行高：</label>
                <el-slider
                  v-model="format.lineHeight"
                  :min="1"
                  :max="3"
                  :step="0.1"
                />
                <span>{{ format.lineHeight }}</span>
              </div>

              <!-- 背景图片预览 -->
              <div class="format-group" v-if="backgroundImageUrl">
                <label>背景图片：</label>
                <div class="background-preview">
                  <img
                    :src="resolveBackgroundImageUrl(backgroundImageUrl)"
                    alt="背景图片预览"
                    class="background-image-preview"
                  />
                  <p class="background-image-name">
                    {{ getBackgroundImageName() }}
                  </p>
                </div>
              </div>
            </div>
          </div>
        </el-form>
      </div>

      <!-- 右侧预览区域 -->
      <div class="right-panel">
        <div class="preview-wrapper">
          <h1>模板预览</h1>
          <div class="certificate-preview" :style="previewStyle">
            <div class="certificate-header">
              <div class="avatar-placeholder"></div>
            </div>
            <div class="certificate-body">
              <div
                v-for="(field, index) in certificateFields"
                :key="'cert-' + index"
                class="preview-field"
                :style="getFieldStyle(field.value)"
                :class="{ selected: currentSelectedField === field.value }"
                @click="selectField(field.value)"
              >
                {{ field.label }}
              </div>
              <div
                v-for="(customField, index) in customFields"
                :key="'custom-' + index"
                class="preview-field"
                :style="getFieldStyle(customField.value)"
                :class="{
                  selected: currentSelectedField === customField.value,
                }"
                @click="selectField(customField.value)"
              >
                {{ customField.value }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="handlePrevStep">上一步</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { createInitialTemplateData } from "@/components/Certificate/template/templateStructure";

export default {
  name: "CertificateTemplateEditor",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    templateId: {
      type: String,
      default: null,
    },
    templateData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      dialogTitle: "新建/编辑证书模板",
      formData: {
        backgroundUrl: null, // 添加背景图URL字段
      },
      certificateFields: [],
      customFields: [],
      newCustomField: "",
      format: {
        fontFamily: "SimHei",
        fontSize: "18",
        color: "#000000",
        alignment: "center",
        letterSpacing: 0,
        lineHeight: 1.2,
        backgroundColor: "#007aff",
        borderColor: "#dcdfe6",
        italic: false,
        underline: false,
        superscript: false,
        subscript: false,
        bold: false,
      },
      isEditMode: false,
      fieldFormats: {},
      currentSelectedField: null,
      defaultFormat: {
        fontFamily: "SimHei",
        fontSize: "18",
        color: "#000000",
        alignment: "center",
        letterSpacing: 0,
        lineHeight: 1.2,
        backgroundColor: "#007aff",
        borderColor: "#dcdfe6",
        italic: false,
        underline: false,
        superscript: false,
        subscript: false,
        bold: false,
      },
      backgroundImageUrl: null,
    };
  },
  mounted() {
    if (this.templateData) {
      this.setTemplateData(this.templateData);
    }
  },
  computed: {
    backgroundImageURL() {
      // 从 formData 或 templateData 中获取背景图片URL
      return (
        this.formData.basicInfo?.backgroundImage ||
        this.formData.backgroundUrl ||
        this.templateData?.basicInfo?.backgroundImage ||
        null
      );
    },
    previewStyle() {
      const style = {
        backgroundColor: this.format.backgroundColor || "#007aff",
        border: `10px solid ${this.format.borderColor || "#dcdfe6"}`,
      };

      // 如果有背景图片，则设置背景图片
      if (this.backgroundImageURL) {
        style.backgroundImage = `url(${this.resolveBackgroundImageUrl(
          this.backgroundImageURL
        )})`;
        style.backgroundSize = "cover";
        style.backgroundRepeat = "no-repeat";
        style.backgroundPosition = "center";
      }

      return style;
    },
    bodyStyle() {
      return {
        textAlign: this.format.alignment,
      };
    },
  },
  methods: {
    // 从查看组件接收数据的新方法
    setTemplateData(data) {
      console.log("编辑器接收到的数据:", data);

      // 重置表单
      this.resetForm();

      if (data && data.fields) {
        // 处理可选字段
        if (data.fields.optionalFields) {
          this.certificateFields = data.fields.optionalFields
            .filter((field) => field.selected)
            .map((field) => ({ label: field.label, value: field.value }));
        }

        // 处理自定义字段
        if (data.fields.customFields) {
          this.customFields = [...data.fields.customFields];
        }

        // 处理字段格式
        if (data.fieldFormats) {
          this.fieldFormats = { ...data.fieldFormats };
        }

        // 设置默认格式
        if (data.format) {
          this.defaultFormat = { ...data.format };
        } else if (data.basicInfo && data.basicInfo.format) {
          this.defaultFormat = { ...data.basicInfo.format };
        }
      }

      // 如果是编辑现有模板，确保所有字段都有格式定义
      this.initFieldFormats();

      // 设置基础信息到 formData
      if (data && data.basicInfo) {
        this.formData.basicInfo = { ...data.basicInfo };
      }
    },
    // 解析背景图片URL
    resolveBackgroundImageUrl(url) {
      // 如果是完整的URL(包含协议)，则直接返回
      if (url.startsWith("http://") || url.startsWith("https://")) {
        return url;
      }

      // 如果是相对路径，则添加基础路径
      if (url.startsWith("/")) {
        // 假设后端资源服务地址为 /api
        return `/api${url}`;
      }

      // 其他情况也加上/api前缀
      return `/api/${url}`;
    },
    // 获取背景图片文件名
    getBackgroundImageName() {
      if (!this.backgroundImageURL) return "";
      const url = this.backgroundImageURL;
      const fileName = url.substring(url.lastIndexOf("/") + 1);
      return fileName.length > 20
        ? fileName.substring(0, 17) + "..."
        : fileName;
    },
    // 确保 initFieldFormats 方法正确初始化所有字段格式
    initFieldFormats() {
      const allFields = [...this.certificateFields, ...this.customFields];
      allFields.forEach((field) => {
        // 如果该字段已经有格式定义，则使用已有格式，否则使用默认格式
        if (!this.fieldFormats[field.value]) {
          this.fieldFormats[field.value] = { ...this.defaultFormat };
        }
      });
    },
    getFieldStyle(value) {
      const format = this.fieldFormats[value] || this.defaultFormat;
      return {
        fontFamily: format.fontFamily,
        fontSize: format.fontSize + "px",
        color: format.color,
        letterSpacing: format.letterSpacing + "px",
        lineHeight: format.lineHeight,
        textAlign: format.textAlign || format.alignment,
        alignment: format.alignment,
        fontWeight: format.bold ? "bold" : "normal",
        fontStyle: format.italic ? "italic" : "normal",
        textDecoration: [
          format.underline ? "underline" : "",
          format.overline ? "overline" : "",
        ]
          .filter(Boolean)
          .join(" "),
        verticalAlign: format.superscript
          ? "super"
          : format.subscript
          ? "sub"
          : "baseline",
      };
    },
    selectField(value) {
      this.currentSelectedField = value;
      // 获取该字段的格式设置，如果没有则使用默认格式
      const format = this.fieldFormats[value] || { ...this.defaultFormat };
      // 更新当前格式面板的值
      this.format = { ...format };
    },
    updateFieldFormat() {
      if (this.currentSelectedField) {
        // 使用 Vue.set 确保响应式更新
        this.$set(this.fieldFormats, this.currentSelectedField, {
          ...this.format,
        });
      }
    },
    toggleItalic(value) {
      this.format.italic = value;
      this.updateFieldFormat();
    },
    toggleUnderline(value) {
      this.format.underline = value;
      this.updateFieldFormat();
    },
    toggleSuperscript(value) {
      this.format.superscript = value;
      this.updateFieldFormat();
    },
    toggleSubscript(value) {
      this.format.subscript = value;
      this.updateFieldFormat();
    },
    toggleBold(value) {
      this.format.bold = value;
      this.updateFieldFormat();
    },

    initFromTemplateData() {
      this.isEditMode = true;

      // 初始化证书字段
      if (this.templateData.fields) {
        this.certificateFields = this.templateData.fields.optionalFields
          .filter((field) => field.selected)
          .map((field) => ({ label: field.label, value: field.value }));
      }

      // 初始化自定义字段
      if (this.templateData.fields && this.templateData.fields.customFields) {
        this.customFields = [...this.templateData.fields.customFields];
      }

      // 初始化格式设置
      if (this.templateData.format) {
        this.defaultFormat = { ...this.templateData.format };
      } else {
        this.defaultFormat = {
          fontFamily: "SimHei",
          fontSize: "18",
          color: "#000000",
          alignment: "center",
          letterSpacing: 0,
          lineHeight: 1.2,
          backgroundColor: "#007aff",
          borderColor: "#dcdfe6",
          italic: false,
          underline: false,
          superscript: false,
          subscript: false,
          bold: false,
        };
      }

      // 为每个字段初始化默认格式
      this.initFieldFormats();
    },

    initFieldFormats() {
      const allFields = [...this.certificateFields, ...this.customFields];
      allFields.forEach((field) => {
        // 如果该字段已经有格式定义，则使用已有格式，否则使用默认格式
        if (!this.fieldFormats[field.value]) {
          this.fieldFormats[field.value] = { ...this.defaultFormat };
        }
      });
    },
    handleClose() {
      this.$emit("update:visible", false);
      this.resetForm();
    },
    resetForm() {
      this.formData = {
        basicInfo: {},
      };
      this.certificateFields = [];
      this.customFields = [];
      this.newCustomField = "";
      this.format = {
        fontFamily: "SimHei",
        fontSize: "18",
        color: "#000000",
        alignment: "center",
        letterSpacing: 0,
        lineHeight: 1.2,
        backgroundColor: "#007aff",
        borderColor: "#dcdfe6",
        italic: false,
        underline: false,
        superscript: false,
        subscript: false,
        bold: false,
      };
      this.currentSelectedField = null;
    },
    addCustomField() {
      if (this.newCustomField.trim()) {
        this.customFields.push({
          value: this.newCustomField.trim(),
          id: Date.now() + Math.random(),
        });
        this.newCustomField = "";
      }
    },
    deleteCustomField(index) {
      this.$confirm("是否确定删除该字段？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.customFields.splice(index, 1);
      });
    },
    editCustomField(index) {
      const oldValue = this.customFields[index].value;
      this.$prompt("请输入新的字段值:", "编辑字段", {
        inputValue: oldValue,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
      })
        .then(({ value }) => {
          if (value.trim()) {
            this.customFields[index].value = value.trim();
          }
        })
        .catch(() => {});
    },
    removeCertificateField(index) {
      this.$confirm("是否确定移除该字段？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.certificateFields.splice(index, 1);
      });
    },
    handlePrevStep() {
      this.$emit("prev-step");
    },
    handleSubmit() {
      const templateData = {
        basicInfo: this.formData.basicInfo || {},
        fields: {
          requiredFields: this.certificateFields.map((f) => f.value),
          optionalFields: this.getAllFieldsWithSelectionState(),
          customFields: [...this.customFields],
        },
        format: { ...this.defaultFormat },
        fieldFormats: { ...this.fieldFormats },
      };

      this.$emit("success", templateData);
      this.handleClose();
    },
    getAllFieldsWithSelectionState() {
      const allFields = [
        { label: "姓名", value: "name", selected: false },
        { label: "证件编号", value: "idNumber", selected: false },
        { label: "培训项目", value: "trainingProject", selected: false },
        { label: "有效年限", value: "validYears", selected: false },
        { label: "发证日期", value: "issueDate", selected: false },
        { label: "起始有效期", value: "startDate", selected: false },
        { label: "截止有效期", value: "endDate", selected: false },
      ];

      return allFields.map((field) => ({
        ...field,
        selected: this.certificateFields.some((f) => f.value === field.value),
      }));
    },
  },
  watch: {
    // 监听格式变化并自动更新当前选中字段的格式
    format: {
      handler(newVal) {
        this.updateFieldFormat();
      },
      deep: true,
    },
  },
};
</script>

<style scoped>
.main-container {
  display: flex;
  height: 600px;
}

.left-panel {
  flex: 1;
  padding: 20px;
  border-right: 1px solid #ebeef5;
  overflow-y: auto;
}

.right-panel {
  width: 400px;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.preview-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.preview-wrapper h3 {
  margin-bottom: 20px;
}

/* 模板样式 预览容器*/
.certificate-preview {
  width: 350px;
  height: 500px;
  border-radius: 10px;
  position: relative;
  overflow: hidden;
}

.certificate-header {
  width: 100%;
  height: 120px;
  display: flex;
  justify-content: center;
  align-items: center;
}


/* 对齐方式 */
.certificate-body {
  width: 100%;
  height: 280px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: white;
  font-size: 16px;
  padding: 20px;
  /* 移除 text-align，让每个字段独立控制 */
  box-sizing: border-box;
}
/* 根据对齐方式调整certificate-body的对齐 */
.certificate-body.left {
  text-align: left;
}

.certificate-body.center {
  text-align: center;
}

.certificate-body.right {
  text-align: right;
}
.preview-field {
  margin: 10px 0;
  /* 确保字段能正确应用文本对齐 */
  width: 100%;
}

.certificate-footer {
  width: 100%;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  color: white;
  font-size: 12px;
}

.date-field {
  margin-bottom: 15px;
}

.section {
  margin-bottom: 20px;
}

.field-list,
.custom-field-list {
  margin-top: 10px;
}

.field-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.field-item:last-child {
  border-bottom: none;
}

.custom-field-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.add-custom-field {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.format-container {
  padding: 10px 0;
}

.format-group {
  margin-bottom: 15px;
}

.format-group label {
  display: inline-block;
  width: 60px;
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
  padding: 20px;
}

.el-button {
  margin-left: 10px;
}

/* 标题 样式 */
.section h1 {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}
.preview-wrapper h1 {
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

/* 添加选中字段的样式 */
.preview-field.selected {
  outline: 2px solid #409eff;
  outline-offset: 2px;
  cursor: pointer;
}
.background-preview {
  margin-top: 10px;
}

.background-image-preview {
  max-width: 100%;
  max-height: 150px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  object-fit: contain;
}

.background-image-name {
  margin: 5px 0 0 0;
  font-size: 12px;
  color: #606266;
  text-align: center;
  word-break: break-all;
}
</style>

